package mysale.dao.impl;

import mysale.pojo.User;

import java.sql.*;

/**
 * @author SnakeWoodMan
 * @create 2020-12-25 11:07
 */
public class UserDaoImpl {
    private Connection con;
    public UserDaoImpl(Connection con){
        this.con = con;
    }


    public User getUserByUserNameAndPassword(String userName, String password) {
        String sql = "SELECT * FROM USER WHERE USERNAME=? AND PASSWORD=? LIMIT 1";
        PreparedStatement pstmt = null;
        ResultSet rs =null;
        User user = null;
        try {
            pstmt = con.prepareStatement(sql);
            pstmt.setString(1, userName);
            pstmt.setString(2, password);
            rs=pstmt.executeQuery();
            while (rs.next()){
                user = new User();
                user.setUid(rs.getInt("uid"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setEmail(rs.getString("email"));
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            try {
                rs.close();
            } catch (SQLException e){
                e.printStackTrace();
            }
            try {
                pstmt.close();
            } catch (SQLException e){
                e.printStackTrace();
            }

        }
        return user;
    }

    public boolean insertUser(User user) {
        String sql = "insert into USER values (NULL,?,?,?,0)";
        PreparedStatement pstmt = null;
        boolean result = false;
        try {
            pstmt = con.prepareStatement(sql);
            pstmt.setString(1, user.getUsername());
            pstmt.setString(2, user.getPassword());
            pstmt.setString(3, user.getEmail());
            if(pstmt.executeUpdate()>0){
                result=true;
            }
        } catch (SQLIntegrityConstraintViolationException e) {//捕获用户名相同的异常
            return false;
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if(pstmt!=null){
                try {
                    pstmt.close();
                }catch (SQLException e){
                    e.printStackTrace();
                }
            }
        }
        return result;
    }
}
